package com.ele.dao.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import com.ele.dao.EmployeeDao;
import com.ele.pojo.Employee;
import com.ele.utils.JDBCUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class EmployeeDaoImpl implements EmployeeDao {
    public List<Employee> findAll() throws SQLException {
        DataSource datasource = JDBCUtils.getDatasource();
        return  Db.use(datasource).query("select * from employee",Employee.class);

    }

    public List<Employee> findEmps(String account, String nickname, String telephone) throws Exception{
        DataSource datasource = JDBCUtils.getDatasource();
        List<Employee> query = Db.use(datasource).query("select * from employee where account=? or  nickname=? or telephone=?", Employee.class, account, nickname, telephone);
        return query;
    }

    @Override
    public Integer updateEmp(Employee employee) throws Exception {
        DataSource ds = JDBCUtils.getDatasource();

            int i = Db.use(ds).update(
                    Entity.create()
                            .set("account", employee.getAccount())
                            .set("password", employee.getPassword())
                            .set("nickname", employee.getNickname())
                            .set("telephone", employee.getTelephone())
                            .set("role", employee.getRole())
                            .set("is_del", employee.getIsDel()),
                    Entity.create("employee").set("id", employee.getId()));

            return i;


    }

    @Override
    public Integer deleteEmpById(String id) throws Exception {
        DataSource datasource = JDBCUtils.getDatasource();
       return Db.use(datasource).del("employee","id",id);
    }

    @Override
    public Integer addEmp(Employee employee) throws Exception {
        DataSource datasource = JDBCUtils.getDatasource();
       return Db.use(datasource).insert(
                Entity.create("employee")
                        .set("account", employee.getAccount())
                        .set("password", employee.getPassword())
                        .set("nickname", employee.getNickname())
                        .set("telephone", employee.getTelephone())
                        .set("role", employee.getRole())
                        .set("is_del", employee.getIsDel()));

    }

    @Override
    public Employee empLogin(String account, String password) throws Exception {
        DataSource datasource = JDBCUtils.getDatasource();
        return Db.use(datasource).query("select * from employee where account = ? and password = ?",
                BeanHandler.create(Employee.class),account,password);

    }

}
